package com.saifan.wyy_ov.ui.communitylife;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.saifan.wyy_ov.R;
import com.saifan.wyy_ov.config.Api;
import com.saifan.wyy_ov.data.bean.BBSPostBean;
import com.saifan.wyy_ov.data.bean.DeletePublishBean;
import com.saifan.wyy_ov.data.bean.RequestBean;
import com.saifan.wyy_ov.model.impl.GetData;
import com.saifan.wyy_ov.model.interfaces.IGetData;
import com.saifan.wyy_ov.model.interfaces.ResponseData;
import com.saifan.wyy_ov.ui.view.BaseActivity;
import com.saifan.wyy_ov.ui.view.RefreshLayout;
import com.saifan.wyy_ov.ui.view.SquareImageView;
import com.saifan.wyy_ov.ui.zoomimage.ZoomImageActivity;
import com.saifan.wyy_ov.utils.CircleProgressBottomDialog;
import com.saifan.wyy_ov.utils.CommonAdapter;
import com.saifan.wyy_ov.utils.ImgUtil;
import com.saifan.wyy_ov.utils.LogUtil;
import com.saifan.wyy_ov.utils.StringUtil;
import com.saifan.wyy_ov.utils.TimeUtils;
import com.saifan.wyy_ov.utils.ToastUtil;
import com.saifan.wyy_ov.utils.ViewHolderHelper;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import lomasky.ma.xui.BaseRecyclerViewAdapter;
import lomasky.ma.xui.BaseViewHolder;
import lomasky.ma.xui.RecyclerViewAdapter;
import lomasky.ma.xui.WrapContentGirdLayoutManager;

/**
 * @version V1.0.0
 * @author: Wangli
 * @date: 2015-6-15 11:19:51
 * @descrption 我的帖子
 */

public class MyPublishActivity extends BaseActivity {
    private android.support.v7.widget.Toolbar toolbar;

    private com.saifan.wyy_ov.ui.view.RefreshLayout refreshLayout;
    private IGetData getData;
    private RequestBean requestBean;
    private int page = 0;

    private List<BBSPostBean> list;
    private boolean initFlag;
    private DeletePublishBean deletePublishBean;
    private android.support.v7.widget.RecyclerView recyclerView;
    RecyclerViewAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setupViews();
        initData();
    }


    private void setupViews() {
        setContentView(R.layout.activity_my_publish);
        this.recyclerView = (RecyclerView) findViewById(R.id.recyclerView);

        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new RecyclerViewAdapter<BBSPostBean>(this, R.layout.mypublish_item) {

            @Override
            public void onBind(BaseViewHolder helper, BBSPostBean item, final int position) {
                helper.setText(R.id.time, TimeUtils.getTime(item.getFTB_FTSJ()));
                helper.setText(R.id.title, StringUtil.returnShow(item.getFTB_BT()));
                helper.setText(R.id.content, StringUtil.returnShow(item.getFTB_LR()));
                helper.setText(R.id.section_name, StringUtil.returnShow(item.getLTBK_MC()));
                helper.setText(R.id.comments_count, String.valueOf(item.getPLTS()));
                RecyclerView imgs = helper.getView(R.id.imgs);
                List<String> imgsPaths = new ArrayList<>();
                if (!StringUtil.isNullOrEmpty(item.getFTB_TPLJ())) {
                    imgsPaths = StringUtil.getStringListByString(item.getFTB_TPLJ(), ",");
                }
                imgs.setLayoutManager(new WrapContentGirdLayoutManager(context, 4));
                imgs.setHasFixedSize(true);
                RecyclerViewAdapter viewAdapter = new RecyclerViewAdapter<String>(context, R.layout.simple_img_item) {

                    @Override
                    public void onBind(BaseViewHolder holder, String item, int position) {
                        holder.setUrl(R.id.img, Api.getUrlIp()+item);

                    }


                };
                viewAdapter.setData(imgsPaths);
                imgs.setAdapter(viewAdapter);


//                if (!StringUtil.isNullOrEmpty(item.getFTB_TPLJ())) {
//                    final String[] imgsPath = item.getFTB_TPLJ().split(",");
//                    for (int i = 0; i < 4; i++) {
//                        int id = getResources().getIdentifier("img" + i, "id", MyPublishActivity.this.getPackageName());
//                        if (i < imgsPath.length) {
//                                helper.getImageView(id).setVisibility(View.VISIBLE);
//                            String p1 = Api.getUrlIp() + imgsPath[i];
////                            helper.setImage(R.id.img0, p1);
//
//                            ImgUtil.DisPlayImg(p1, helper.getImageView(R.id.img0), context);
//                            final int finalI = i;
//                            helper.getView(id).setOnClickListener(new View.OnClickListener() {
//                                @Override
//                                public void onClick(View v) {
//                                    Intent intent = new Intent(MyPublishActivity.this, ZoomImageActivity.class);
//                                    ArrayList<String> imgs = new ArrayList<String>();
//                                    for (int m = 0; m < imgsPath.length; m++) {
//                                        imgs.add(imgsPath[m]);
//                                    }
//                                    intent.putStringArrayListExtra("img", imgs);
//                                    intent.putExtra("position", finalI);
//                                    startActivity(intent);
//                                }
//                            });
//                        } else {
//                            helper.getView(id).setVisibility(View.INVISIBLE);
//                        }
//                    }
//                }
                ImageButton imageButton = helper.getView(R.id.delete);
                imageButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        showDelete(position);
                    }
                });
            }


        };
        recyclerView.setAdapter(adapter);

        this.refreshLayout = (RefreshLayout) findViewById(R.id.refreshLayout);

        this.toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        list = new ArrayList<BBSPostBean>();

        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 0;
                refreshLayout.setRefreshing(true);
                initData();
            }
        });
        refreshLayout.setOnLoadListener(new RefreshLayout.OnLoadListener() {
            @Override
            public void onLoad() {
                CircleProgressBottomDialog.showDialog(MyPublishActivity.this);
                if (page > 0)
                    refreshLayout.setLoading(true);
                page++;
                initData();
            }
        });
        adapter.setOnItemClickListener(new BaseRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int i) {
                Intent intent = new Intent(MyPublishActivity.this, BBSDetailsActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("data", (Serializable) list.get(i));
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
    }

    private void initData() {
        String tip;
        if (requestBean == null) {
            requestBean = new RequestBean();
            requestBean.setUserID(getRoomInfoBean().getWYKHDA_ZJ());
        }
        requestBean.setPage(page);
        if (getData == null)
            getData = new GetData();
        if (initFlag)
            tip = "";
        else
            tip = "正在加载...";
        getData.getDataJson(MyPublishActivity.this, Api.BBS.MYPOSTSLIST, requestBean, tip, new ResponseData() {
            @Override
            public void onSuccess(String json) {
                LogUtil.d("我的发布" + json);
                if (StringUtil.isNullOrEmpty(json)) {
                    if (page == 0) {
                        handler.sendEmptyMessage(0);//没有数据
                    } else {
                        page--;
                        handler.sendEmptyMessage(1);//没有更多数据
                    }
                } else {
                    Message message = handler.obtainMessage();
                    List<BBSPostBean> tempList = (new Gson()).fromJson(json, new TypeToken<List<BBSPostBean>>() {
                    }.getType());
                    if (page == 0) {//下拉刷新
                        if (tempList != null && tempList.size() > 0) {
                            message.what = 2;
                            message.obj = tempList;
                        } else {
                            message.what = 0;
                        }
                    } else {//加载更多
                        if (tempList != null && tempList.size() > 0) {
                            message.what = 3;
                            message.obj = tempList;
                        } else {
                            message.what = 1;
                            page--;
                        }
                    }
                    handler.sendMessage(message);
                    CircleProgressBottomDialog.closeDialog();
                }
                initFlag = true;
            }

            @Override
            public void onFailed(String str) {
                refreshLayout.setRefreshing(false);
                refreshLayout.setLoading(false);
                CircleProgressBottomDialog.closeDialog();
                if (page >= 0) {
                    page--;
                }
            }
        });
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:

                    ToastUtil.showToast(MyPublishActivity.this, "暂无相关数据");
                    refreshLayout.setRefreshing(false);
                    refreshLayout.setLoading(false);
                    break;
                case 1:
//                    ToastUtil.showToast(BBSListActivity.this, "暂无更多数据");
                    refreshLayout.setRefreshing(false);
                    refreshLayout.setLoading(false);
                    break;
                case 2:

                    list = (List<BBSPostBean>) msg.obj;
                    adapter.setData(list);
                    adapter.notifyDataSetChanged();
                    refreshLayout.setRefreshing(false);
                    refreshLayout.setLoading(false);
                    break;
                case 3:
                    list.addAll((List<BBSPostBean>) msg.obj);
                    adapter.setData(list);
                    adapter.notifyDataSetChanged();
                    refreshLayout.setRefreshing(false);
                    refreshLayout.setLoading(false);
                    break;
                default:
                    break;
            }
        }
    };

    private void showDelete(final int position) {
        AlertDialog alertDialog = new AlertDialog.Builder(MyPublishActivity.this)
                .setTitle("确定删除 " + StringUtil.returnShow(list.get(position).getFTB_BT()) + " ?")
                .setNegativeButton("删除", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        deletePublish(position);
                    }
                })
                .setPositiveButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .create();
        alertDialog.show();
    }

    private void deletePublish(final int position) {

        deletePublishBean = new DeletePublishBean();
        deletePublishBean.setFTB_KHWJ(getRoomInfoBean().getWYKHDA_ZJ());
        deletePublishBean.setFTB_ZJ(list.get(position).getFTB_ZJ());
        getData.getDataJson(MyPublishActivity.this, Api.BBS.DELETEPOSTS, deletePublishBean, "正在删除...", new ResponseData() {
            @Override
            public void onSuccess(String json) {
                ToastUtil.showToast(MyPublishActivity.this, "删除成功");

                adapter.remove(position);
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onFailed(String str) {

            }
        });
    }
}
